package com.jason.www.code.impl;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.jason.www.code.IPayClient;
import com.jason.www.commons.PropertyConfigurer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Map;

import static com.alipay.api.AlipayConstants.CHARSET_UTF8;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;

@Service("newAlipayClient")
@Slf4j
public class NewAlipayClient  implements IPayClient {


    public static final String ALIPAY_GATEWAY = "https://openapi.alipay.com/gateway.do";
    public static final String TRADE_FINISHED = "TRADE_FINISHED";
    public static final String TRADE_SUCCESS = "TRADE_SUCCESS";

    @Autowired
    private PropertyConfigurer propertyConfigurer;

    private AlipayClient alipayClient;

    @PostConstruct
    public void prepareConfigAndClient() {
        alipayClient = new DefaultAlipayClient(ALIPAY_GATEWAY, propertyConfigurer.getAlipayAppId(), propertyConfigurer.getAlipayPrivateKey(), "json", CHARSET_UTF8, propertyConfigurer.getAlipayPublicKey(), "RSA2");
    }

    @Override
    public String buildRequestUrl(Map<String, String> requestParams) {
        try {
            AlipayRequest alipayTradePayRequest = construct(requestParams);
            String body = alipayClient.pageExecute(alipayTradePayRequest).getBody();
            log.info("body::{}",body);
            return body;
        } catch (AlipayApiException e) {
            log.error(e.getErrMsg(), e);
        }
        return StringUtils.EMPTY;
    }

    /**
     * @param params
     * @return
     */
    @Override
    public Boolean verifyCallbackHmac(Map<String, String> params) {
        return true;
    }


    public AlipayRequest construct(Map<String, String> requestParams) {
        AlipayRequest alipayRequest = bindCommonField(requestParams);
        AlipayTradePayModel bizModel = getBizModel(requestParams);
        alipayRequest.setBizModel(bizModel);
        return alipayRequest;
    }


    private AlipayTradePayModel getBizModel(final Map<String, String> requestParams) {
        AlipayTradePayModel model = new AlipayTradePayModel();
        model.setOutTradeNo(requestParams.get("orderId"));
        model.setSubject(requestParams.get("subject"));
        model.setTotalAmount(requestParams.get("totalPrice"));
        model.setSellerId(propertyConfigurer.getAlipayPartner());
        model.setProductCode("QUICK_WAP_PAY");
        if (isNotEmpty(requestParams.get("timeout"))) {
            model.setTimeoutExpress(requestParams.get("timeout"));
        }
        return model;

    }

    public AlipayRequest bindCommonField(Map<String, String> requestParams) {
        AlipayRequest alipayRequest = new AlipayTradeWapPayRequest();
        String baseUri = requestParams.get("requestUrl");
        String returnUrl = requestParams.get("returnUrl");
        String notifyUrl = requestParams.get("notifyUrl");
        if (propertyConfigurer.getOverhttps().equalsIgnoreCase("Y")
                && baseUri.startsWith("http://")) {
            baseUri = baseUri.replace("http://", "https://");
        }
        alipayRequest.setReturnUrl(baseUri + (isNotEmpty(returnUrl)? returnUrl : propertyConfigurer.getReturnUrl()));
        alipayRequest.setNotifyUrl(baseUri + (isNotEmpty(notifyUrl)? notifyUrl : propertyConfigurer.getNotifyUrl()));
        log.info("构造支付宝支付报文: NotifyUrl：：" + alipayRequest.getNotifyUrl());
        log.info("构造支付宝支付报文: ReturnUrl::" + alipayRequest.getReturnUrl());
        return alipayRequest;
    }

}
